local audio = require("framework.audio")
local audioPath = require("app.res.audio.config")
local Matrix_left = require("app.views.matrix_left")
local Matrix_right = require("app.views.matrix_right")
local StartDialog = require("app.views.startDialog")
local ResultDialog = require("app.views.resultDialog")
local levelManger = require("app.manger.levelManger")
local recordManger = require("app.manger.recordManger")
local ImgNumber = require("app.views.imgNumber")
local scheduler = require("framework.scheduler")
local device = require("framework.device")

local M = class("gameScene", function()
    return display.newScene("gameScene")
end)

local TextTab = {
    ["0"] = "#text_0.png",
    ["1"] = "#text_1.png",
    ["2"] = "#text_2.png",
    ["3"] = "#text_3.png",
    ["4"] = "#text_4.png",
    ["5"] = "#text_5.png",
    ["6"] = "#text_6.png",
    ["7"] = "#text_7.png",
    ["8"] = "#text_8.png",
    ["9"] = "#text_9.png",
    [":"] = "#text_mao.png",
}

function M:ctor()
    cc.ui.UILabel.new({
            UILabelType = 2, text = "Hello, World", size = 64})
        :align(display.CENTER, display.cx, display.cy)
        :addTo(self)
    self.m_score = 0
    local bg = display.newSprite("images/bg_1.png")
    	:align(display.CENTER, display.cx, display.cy)
        :addTo(self)
    local size = bg:getContentSize()
    dump(size)
    self.matrix_right = Matrix_right:new{success = handler(self, self.success),lose = handler(self, self.lose),addScore = handler(self, self.addScore)}
        :addTo(bg)
        :align(display.RIGHT_CENTER,size.width-148,size.height*0.5-10)

    self.matrix_left = Matrix_left:new()
        :scale(0.6)
        :addTo(bg)
        :align(display.RIGHT_CENTER,size.width-148-self.matrix_right:getContentSize().width-60,size.height*0.5-100)
        
    self.levelLabel = ImgNumber:new(TextTab)
        :color(cc.c3b(42,255,160))
        :addTo(bg)
        :pos(383,425)
        :scale(0.2)
        :setNumber(1)

    self.timeLabel = ImgNumber:new(TextTab)
        :color(cc.c3b(67,255,255))
        :addTo(bg)
        :pos(340,488)
        :scale(0.3)
        :setNumber("10:00")

    self.scoreLabel = ImgNumber:new(TextTab)
        :color(cc.c3b(255,222,36))
        :addTo(bg)
        :pos(203,475)
        :scale(0.32)
        :setNumber(0)


    self:addBackEvent()
    
    StartDialog.new(handler(self, self.startLevel))
        :addTo(self)
end

local showTime = 0
local operateTime = 0
local levelStatus = 0 --0:左边显示预览，1:左边停止预览，2:关闭关卡
local levelTime = 0 --当前关卡过了多少时间
local updateHander = nil --定时器句柄

local function resetLevel()
    levelStatus = 2
    levelTime = 0
    if updateHander~=nil then
        scheduler.unscheduleGlobal(updateHander)
        updateHander = nil
    end
end

function M:addScore(score)
    self.m_score = self.m_score + score
    self.scoreLabel:setNumber(self.m_score)
    recordManger:updateScore(self.m_score)
end

--开始下一关
function M:startLevel()
    audio.stopMusic(false)
    audio.playMusic(audioPath.gameBg)
    -- print(string.format("----------------------开始第%s关,%s",levelManger:getLevel(),os.clock()))
    local levelData = levelManger:getLevelData()
    self.matrix_right:setData(levelData)
          :showGirds()
    self.matrix_left:setData(levelData)
          :showGirds()
    showTime = levelManger:getShowTime()
    operateTime = levelManger:getOperateTime()
    levelStatus = 0
    if updateHander~=nil then
        scheduler.unscheduleGlobal(updateHander)
        updateHander = nil
    end
    updateHander = scheduler.scheduleGlobal(handler(self, self.updateTime),0.1)
end

function M:updateTime(f)
    levelTime = levelTime + f
    if levelTime<=operateTime then
        local leftTime = operateTime - levelTime
        local tmp = "0"..math.floor(leftTime)
        local tmp2 = tonumber(string.format("%0.2f", leftTime-tmp))*100
        self.timeLabel:setNumber(tmp..":"..tmp2)
    end
    if levelTime>= showTime and levelStatus==0 then
        self.matrix_left:runFadeOutAni()
        levelStatus = 1
    elseif levelTime>=operateTime and levelStatus==1 then
        self.timeLabel:setNumber("00:00")
        resetLevel()
        self:lose()
    end
end

--闯关成功
function M:success()
    resetLevel()
    -- print(string.format("成功,level=%s,time=%s",levelManger:getLevel(),os.clock()))
    audio.playSound(audioPath.levelWin)
    levelManger:levelUp()
    self.levelLabel:setNumber(levelManger:getLevel())
    --开启下一关
    self.matrix_right:runNextLevelAni()
    self:startLevel()
end

--闯关失败
function M:lose()
    -- print(string.format("失败,level=%s,time=%s",levelManger:getLevel(),os.clock()))
    resetLevel()
    self.matrix_left:runBlink()
    audio.playSound(audioPath.result)
    self:performWithDelay(function ( ... )
        ResultDialog.new{curScore = self.m_score,share = function ( ... )
                  end,
            restart = function ( ... )
              self.matrix_left:clearGirds()
              self.matrix_right:clearGirds()
              levelManger:resetLevel()
              self.levelLabel:setNumber(levelManger:getLevel())
              self.timeLabel:setNumber("10:00")
              self.m_score = 0
              self.scoreLabel:setNumber(self.m_score)
              self:performWithDelay(function (  )
                  StartDialog.new(handler(self, self.startLevel))
                    :addTo(self)
              end, 0.6)
        end}
            :addTo(self)
    end, 1.2)
end


function M:addBackEvent()  
    if device.platform == "android" then  
        self:addNodeEventListener(cc.KEYPAD_EVENT, function(event)  
            if event.key == "back" then    
                -- require("app.MyApp").new():enterScene("startScene")
                device.showAlert("hyz", "确定退出游戏 ?", {"YES", "NO"}, function (event)
                    if event.buttonIndex == 1 then
                        cc.Director:getInstance():endToLua()  
                    else
                    end
                end)
            end  
        end)  
        self:setKeypadEnabled(true)  
    end   
end  

function M:onEnter()
end

function M:onExit()
end

return M
